<template>
  <div class="contaienr">
    <van-address-list
      v-model="chosenAddressId"
      :list="addressList"
      :switchable="isChoose"
      :show-area="false"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    >
    <div class="no-data" slot="top" v-if="!addressList.length">
      {{noTips}}
    </div>
    </van-address-list>
  </div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
let flag
export default {
  data() {
    return {
      chosenAddressId: '',
      addressList: [],
      noTips: '您还没有地址信息',
      isChoose: false
    }
  },
  created() {
    this.getAddressList()
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    ...mapMutations(['updateDefaultAddress']),
    /**
     * 获取收货地址
     */
    getAddressList() {
      const query = {
        userId: this.user.id
      }
      this.$api.cart.getAddressList(query).then(res => {
        if (res.code === 200) {
          this.addressList = res.data.map(item => {
            return {
              id: item.id,
              name: item.consigneeName,
              tel: item.consigneePhone,
              address: item.address
            }
          })
        }
      })
    },
    onAdd() {
      this.$router.push({ path: 'address-edit' })
    },
    onEdit(item) {
      this.$router.push({ path: 'address-edit', query: { id: item.id }})
    },
    onSelect(item) {
      if (!this.isChoose) return
      // ?会触发2次方法
      if (!flag) {
        flag = true
        this.$router.back(-1)
        this.updateDefaultAddress(item)
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .no-data{
    font-size: 16px;
    color:#999;
    text-align: center;
    padding-top: 150px;
  }
</style>

